package com.yiwei.zhh.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yiwei.zhh.R;
import com.yiwei.zhh.constant.Const;
import com.yiwei.zhh.http.InfoCallBack;
import com.yiwei.zhh.impl.ChsiInfoImpl;
import com.yiwei.zhh.model.ChsiRegisterModel;
import com.yiwei.zhh.util.DisplayUtil;
import com.yiwei.zhh.util.JsonUtil;
import com.yiwei.zhh.util.StatusBarCompat;
import com.yiwei.zhh.util.ToastUtil;
import com.yiwei.zhh.util.UI;
import com.yiwei.zhh.util.Util;
import com.yiwei.zhh.view.CircularProgress;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.Unbinder;

/**
 * 学信网注册界面
 * Created by Master.Dong on 16/4/10.
 */
public class ChsiRegisterV2Activity extends BaseActivity {

    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.cb_agree)
    CheckBox cbAgree;
    @BindView(R.id.progressBar)
    CircularProgress loading;
    @BindView(R.id.btn_code)
    TextView btnCode;
    @BindView(R.id.layout_view1)
    LinearLayout layoutView1;
    @BindView(R.id.edit_realname)
    EditText editRealname;
    @BindView(R.id.edit_cardno)
    EditText editCardno;
    @BindView(R.id.edit_password)
    EditText editPassword;
    @BindView(R.id.cb_see)
    CheckBox cbSee;
    @BindView(R.id.layout_view2)
    LinearLayout layoutView2;
    @BindView(R.id.txt_agree)
    TextView txtAgree;
    @BindView(R.id.forget)
    TextView forget;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.edit_code_img)
    EditText editCodeImg;
    @BindView(R.id.img_code)
    ImageView imgCode;
    @BindView(R.id.img_code_view)
    LinearLayout imgCodeView;
    @BindView(R.id.btn_back)
    ImageView btnBack;


    private boolean isSend;

    private Unbinder unbiner;
    private int viewIndex = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chsi_register_v2_activity);
        unbiner = ButterKnife.bind(this);
        baseInitView(this, "ChsiRegisterV2Activity", Const.ViewType.ACTIVITY);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintColor(Color.TRANSPARENT);
            tintManager.setNavigationBarTintColor(Color.parseColor("#000000"));
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setNavigationBarTintEnabled(true);
        }
        initView();

    }

    private void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            btnBack.post(new Runnable() {
                @Override
                public void run() {
                    int height = StatusBarCompat.getStatusBarHeight(ChsiRegisterV2Activity.this);
                    if (height == 0) {
                        return;
                    }
                    int left = DisplayUtil.dip2px(ChsiRegisterV2Activity.this, 10);
                    btnBack.setPadding(left, height + left, 0, left);
                }
            });
        }
        editPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11) {
                    if (checkMobile())
                        getCheckMobile();
                } else imgCodeView.setVisibility(View.GONE);
            }
        });
        cbSee.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cbSee.setBackgroundResource(R.mipmap.see_off);
                    editPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); //显示密码
                } else {
                    cbSee.setBackgroundResource(R.mipmap.see);
                    editPassword.setTransformationMethod(PasswordTransformationMethod.getInstance()); //隐藏密码
                }
                editPassword.setSelection(editPassword.getText().length());
            }
        });
    }

    private boolean mark = false;

    @OnTextChanged({R.id.edit_code_img, R.id.edit_code})
    void afterTextChanged(android.text.Editable s) {
        if (UI.toString(editCodeImg).length() != 0 && UI.toString(editCode).length() != 0) {
//            填完了数据
            Log.i("dasdasda", "执行第一步mark=" + mark);
            if (!mark) {
                mark = true;
                btnSubmit.setBackgroundResource(R.drawable.btn_chsi_register_true);
                Log.i("dasdasda", "执行第一步");
            }
        } else {
            Log.i("dasdasda", "执行第二步mark=" + mark);
//            还没填完
            if (mark) {
                mark = false;
                btnSubmit.setBackgroundResource(R.drawable.btn_chsi_register);
                Log.i("dasdasda", "执行第二步");
            }
        }
    }

    private boolean markSec = false;

    @OnTextChanged({R.id.edit_cardno, R.id.edit_password, R.id.edit_realname})
    void afterTextChanged1(android.text.Editable s) {
        if (UI.toString(editCardno).length() != 0 && UI.toString(editPassword).length() != 0 && UI.toString(editRealname).length() != 0) {
            if (!markSec) {
                markSec = true;
                btnSubmit.setBackgroundResource(R.drawable.btn_chsi_register_true);
            }
        } else {
            if (markSec) {
                markSec = false;
                btnSubmit.setBackgroundResource(R.drawable.btn_chsi_register);
            }
        }
    }

    /**
     * 验证码计时器
     */
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            btnCode.setEnabled(false);
            btnCode.setText((millisUntilFinished / 1000) + getResources().getString(R.string.resend));
            btnCode.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray));
        }

        @Override
        public void onFinish() {
            resetBtn();
        }
    };

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        btnCode.setEnabled(true);
        if (isSend)
            btnCode.setText(getResources().getString(R.string.send_code_again));
        else
            btnCode.setText(getResources().getString(R.string.get_code));
        btnCode.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();

    }

    /**
     * 是否显示加载框
     *
     * @param b
     */
    private void showLoading(boolean b) {
        if (b) {
            if (loading != null) loading.setVisibility(View.VISIBLE);
        } else {
            if (loading != null) loading.setVisibility(View.GONE);
        }
    }

    /**
     * 验证手机号
     *
     * @return
     */
    private boolean checkMobile() {
        if (TextUtils.isEmpty(editPhone.getText().toString().trim())) {
            ToastUtil.makeText(ChsiRegisterV2Activity.this, getString(R.string.phone_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!Util.isMobileNO(editPhone.getText().toString().trim())) {
            ToastUtil.makeText(ChsiRegisterV2Activity.this, getString(R.string.phone_is_error2), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 检查验证码
     *
     * @return
     */
    private boolean checkImgCode() {
        if (TextUtils.isEmpty(editCode.getText().toString().trim())) {
            ToastUtil.makeText(ChsiRegisterV2Activity.this, getString(R.string.img_code_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 检查验证码
     *
     * @return
     */
    private boolean checkCode() {
        if (TextUtils.isEmpty(editCode.getText().toString().trim())) {
            ToastUtil.makeText(ChsiRegisterV2Activity.this, getString(R.string.sms_code_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 检查姓名、身份证、密码非空
     *
     * @return
     */
    private boolean checkView2Input() {
        if (TextUtils.isEmpty(editRealname.getText().toString().trim())) {
            ToastUtil.makeText(this, getString(R.string.realname_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(editCardno.getText().toString().trim())) {
            ToastUtil.makeText(this, getString(R.string.idcard_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(editPassword.getText().toString().trim())) {
            ToastUtil.makeText(this, getString(R.string.password_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (editPassword.getText().toString().trim().length() < 6) {
            ToastUtil.makeText(this, getString(R.string.pwd_is_under_6), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 验证手机号
     */
    private void getCheckMobile() {
        showLoading(true);
        new ChsiInfoImpl().getCheckMobileInfo(this, editPhone.getText().toString().trim(), new InfoCallBack() {
            @Override
            public void onSuccess(Object o) {
                showLoading(false);
                if (o.toString().equals("true")) {
                    imgCodeView.setVisibility(View.VISIBLE);
                    getImgCode();
                } else
                    ToastUtil.makeText(getApplicationContext(), getString(R.string.mobile_already_register), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(String cause) {
                showLoading(false);
                ToastUtil.makeText(getApplicationContext(), cause, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getCodeInfo() {
        showLoading(true);
        new ChsiInfoImpl().getCodeInfo(this, editPhone.getText().toString().trim(), editCodeImg.getText().toString().trim(), new InfoCallBack() {
            @Override
            public void onSuccess(Object o) {
                showLoading(false);
                ChsiRegisterModel model = JsonUtil.fromJson(o.toString(), ChsiRegisterModel.class);
//                RBLog.i("----  ", model.getStatus() + "    " + model.getTips() + "   " + model.getTipsNote() + "    " + model.getTipsBtnValue());

                String tips = model.getTips();
                if (model.getStatus().equals("0")) {
                    if (tips.contains("[") && tips.contains("]")) {
                        ToastUtil.makeText(getApplicationContext(), tips.substring(tips.indexOf("[") + 1, tips.lastIndexOf("]")), Toast.LENGTH_SHORT).show();
                        if (tips.contains(getString(R.string.code1))) getImgCode();
                    }
                    resetBtn();
                } else if (model.getStatus().equals("2")) {
                    isSend = true;
                    ToastUtil.makeText(getApplicationContext(), tips, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String cause) {
                showLoading(false);
                resetBtn();
                ToastUtil.makeText(getApplicationContext(), cause, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 获取图形验证码
     */
    private void getImgCode() {
        showLoading(true);
        new ChsiInfoImpl().getImgCodeInfo(this, new InfoCallBack() {
            @Override
            public void onSuccess(Object o) {
                showLoading(false);
                Bitmap bitmap = (Bitmap) o;
                imgCode.setImageBitmap(bitmap);
            }

            @Override
            public void onFailure(String cause) {
                showLoading(false);
                ToastUtil.makeText(getApplicationContext(), cause, Toast.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * 获取注册信息
     */
    private void getRegisterInfo(String phone, String code, String realname, String idno, String password) {
        showLoading(true);
        new ChsiInfoImpl().getRegisterInfo(this, phone, code, realname, idno, password, new InfoCallBack() {
            @Override
            public void onSuccess(Object o) {
                showLoading(false);
                if (o.toString().contains(getString(R.string.idno_already_register)))
                    ToastUtil.makeText(getApplicationContext(), getString(R.string.idno_already_register), Toast.LENGTH_SHORT).show();
                else if (o.toString().contains(getString(R.string.idno_is_error)))
                    ToastUtil.makeText(getApplicationContext(), getString(R.string.idno_is_error), Toast.LENGTH_SHORT).show();
                else if (o.toString().contains(getString(R.string.code_is_error)))
                    ToastUtil.makeText(getApplicationContext(), getString(R.string.code_is_error), Toast.LENGTH_SHORT).show();
                else if (o.toString().contains(getString(R.string.register_success))) {
                    ToastUtil.makeText(getApplicationContext(), getString(R.string.register_success), Toast.LENGTH_SHORT).show();
                    finish();
                }
            }

            @Override
            public void onFailure(String cause) {
                showLoading(false);
                ToastUtil.makeText(getApplicationContext(), cause, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @OnClick({R.id.btn_code, R.id.txt_agree, R.id.forget, R.id.btn_submit, R.id.btn_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_code:
                if (imgCodeView.getVisibility() == View.GONE) {
                    if (checkMobile())
                        getCheckMobile();
                } else {
                    if (checkMobile() && checkImgCode()) {
                        timer.start();
                        getCodeInfo();
                    }
                }
                break;
            case R.id.txt_agree:
                Intent intent = new Intent(this, AboutActivity.class);
                intent.putExtra("id", Const.ContractType.CHSI);
                intent.putExtra("type", 1);
                intent.putExtra("title", getResources().getString(R.string.service_contract_text2));
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.forget:
                finish();
                Util.startActivity(this, ChsiForgetPwdV2Activity.class);
                break;
            case R.id.btn_submit:
                if (!cbAgree.isChecked())
                    ToastUtil.makeText(this, getResources().getString(R.string.please_agree_server), Toast.LENGTH_SHORT).show();
                else {
                    if (layoutView1.getVisibility() == View.VISIBLE) {
                        if (checkMobile() && checkCode()) {
                            showView(2);
                        }
                    } else if (layoutView2.getVisibility() == View.VISIBLE) {
                        if (checkView2Input())
                            getRegisterInfo(editPhone.getText().toString(), editCode.getText().toString(), editRealname.getText().toString(), editCardno.getText().toString(), editPassword.getText().toString());
                    }
                }
                break;
            case R.id.btn_back:
                if (viewIndex == 2) {
                    showView(1);
                } else finish();
                break;
        }
    }

    /**
     * 显示的界面
     *
     * @param index
     */
    private void showView(int index) {
        if (index == 2) {  //显示界面二
            viewIndex = 2;
            layoutView1.setVisibility(View.GONE);
            layoutView2.setVisibility(View.VISIBLE);
            forget.setVisibility(View.GONE);
            btnSubmit.setText(getString(R.string.finish));
        } else {  //显示界面一
            viewIndex = 1;
            layoutView1.setVisibility(View.VISIBLE);
            layoutView2.setVisibility(View.GONE);
            forget.setVisibility(View.VISIBLE);
            btnSubmit.setText(getString(R.string.next));
        }
    }
}
